package com.ias.agdis_r.netservice;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import android.util.Log;

import com.ias.agdis_r.R;
import com.ias.agdis_r.action.task.TaskReceiveAction;
import com.ias.agdis_r.activity.MainActivity;
import com.ias.agdis_r.bean.document.Document;
import com.ias.agdis_r.bean.document.DocumentResult;
import com.ias.agdis_r.bean.fight.FlightQueryValueChanged;
import com.ias.agdis_r.bean.fight.Query;
import com.ias.agdis_r.bean.fight.QueryParams;
import com.ias.agdis_r.bean.fight.SubFlightInfo;
import com.ias.agdis_r.bean.message.MessageTemplates;
import com.ias.agdis_r.bean.task.Task;
import com.ias.agdis_r.bean.user.UserInfoBean;
import com.ias.agdis_r.db.BoxDBHelper;
import com.ias.agdis_r.db.MyBeanTempDBHelper;
import com.ias.agdis_r.db.message.MessageUtil;
import com.ias.agdis_r.db.message.MyMessageBean;
import com.ias.agdis_r.impl.security.SecurityResponseImpl;
import com.ias.agdis_r.manager.ActionManager;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.DataManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.manager.FindLuggageDataManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.manager.MessageManager;
import com.ias.agdis_r.manager.ServiceManage;
import com.ias.agdis_r.manager.ThreadManager;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.module.ParameterModel;
import com.ias.agdis_r.terminalmanager.restful.findluggage.vo.FindLuggageInfoResponseVO;
import com.ias.agdis_r.terminalmanager.restful.workgroup.vo.Member;
import com.ias.agdis_r.terminalmanager.restful.workgroup.vo.WorkGroupLoadMembersResponseVO;
import com.ias.agdis_r.util.FlnChangeUtils;
import com.ias.agdis_r.util.MyMessage;
import com.ias.agdis_r.util.S;
import com.ias.agdis_r.util.ShowToast;
import com.ias.agdis_r.util.TaskUtil;
import com.ias.agdis_r.util.sdcard.WriteLog;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;

/**
 * 接收消息
 * 
 * @author wanghu
 * 
 */
public class ReceiveMessageThread implements Runnable {

	public static final String ACTION_MESSAGE_ARRIVED = "com.ias.agdis_r.action.messageArrive";

	private BaseService service;
	private boolean closed = false;
	// add by huzedong
	private String messagetemp = "";
	private Context context = DataBaseManager.getInstance().getContext();

	public ReceiveMessageThread(BaseService service) {
		this.service = service;
		new Thread(this).start();
	}

	public void closeRun() {
		closed = true;
		System.out.println("############socket is disconnect################Recv");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		//Looper.prepare();
		while (!closed) {
			try {
				while (service.getSelector().select(5000) > 0) {
					// 遍历每个有可用IO操作Channel对应的SelectionKey
					String message = "";
					for (SelectionKey sk : service.getSelector().selectedKeys()) {
						// 如果该SelectionKey对应的Channel中有可读的数据
						if (sk.isReadable()) {
							// 使用NIO读取Channel中的数据
							SocketChannel sc = (SocketChannel) sk.channel();
							ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
							ByteBuffer buffer1 = ByteBuffer.allocateDirect(1024);
							buffer.clear();
							buffer1.clear();
							int count = 0;
							int allCount = 0;
							try {
								int i = 0;
								while ((count = sc.read(buffer1)) > 0 && allCount < 10240) {
									buffer1.flip();
									if (i != 0) {
										byte[] bytes = new byte[buffer.limit()];
										buffer.get(bytes, 0, buffer.limit());
										int m_recvcapacity = buffer.capacity();
										buffer = ByteBuffer.allocate(m_recvcapacity + 1024);
										buffer.put(bytes);
									}
									Thread.sleep(10); // 为防止写入数据不正确，加入此行
									buffer.put(buffer1);
									buffer1.clear();
									buffer.flip();
									// 为下一次读取作准备
									i++;
									allCount += count;
								}
								i = 0;
								if (buffer.limit() != 0) {
									String receivedString = Charset.forName("GBK").newDecoder().decode(buffer)
											.toString();
									message = receivedString;
									buffer.clear();
								}

								if (count < 0) {
									EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TEMP, context.getString(R.string.readLenth) + count, false);

									System.out.println("############socket counts disconnect################被动断开");
									WriteLog.getInstance().writeLog("socket counts disconnect################被动断开");
									service.close();
								}
							} catch (Exception e) {
								System.out.println("############sc.read Exception################11");
								sk.cancel();
								service.getSelector().selectedKeys().remove(sk);
								e.printStackTrace();
							}
							// 为下一次读取作准备
							// sk.interestOps(SelectionKey.OP_READ);
						}
						service.getSelector().selectedKeys().remove(sk);
					}
					System.out.println("接收消息：" + message);
					// 分离处理消息
					handleMessage(message);
				}
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("############socket is disconnect################11");
				service.close();
			}
		}
		//Looper.loop();
	}

	/**
	 * 处理SOCKET读取出来的消息，将粘连的消息分离处理
	 * 
	 * @param message
	 * @author zhangsc
	 */
	public void handleMessage(String message) {
		int n = 0;
		// 如果消息不是以@@结尾的
		if (!message.endsWith("@@")) {
			n = -1;
		}
		// 处理服务器发送间隔短时,几条数据当一条返回的问题
		String[] arrmsg = message.split("@@");
		if (arrmsg.length > 0) {
			for (int i = 0; i < arrmsg.length; i++) {
				// 如果消息为空
				if (S.isEmpty(arrmsg[i])) {
					continue;
				} else if (i < arrmsg.length + n) {
					// 针对于第一条消息前有@进行处理
					// 例如@##test
					if (arrmsg[i].indexOf("@") > -1) {
						// 将@字符截取掉
						arrmsg[i] = arrmsg[i].substring(arrmsg[i].indexOf("@") + 1, arrmsg[i].length());
					}
					// 将消息加上@@
					arrmsg[i] += "@@";
					// 如果消息不是以##开始的
					// 例如 test@@ ，#test@@
					if (arrmsg[i].indexOf("##") == -1) {
						// 将上次记录的消息部分与这部分消息进行组合
						// add by huzedong
						messagetemp = messagetemp + arrmsg[i];
						// 如果是以##开始，@@结尾的话，执行消息
						if (messagetemp.startsWith("##") && messagetemp.endsWith("@@")) {
							// 解析消息
							// add by huzedong
							operationMessage(checkMessage(messagetemp));
						}
						// 清空消息片段
						// add by huzedong
						messagetemp = "";
					} else {
						// 解析消息
						operationMessage(checkMessage(arrmsg[i]));
					}
				}
				// 如果是最末尾结尾的，且不包含@@的信息
				// 例##test、#、##、##test@
				else { // add by huzedong
						// 保存消息片段
					messagetemp = arrmsg[i];
					// 如果此条消息格式为##test@
					if (messagetemp.indexOf("##") > -1 && messagetemp.indexOf("@") > -1) {
						// 为消息补上一个@
						messagetemp = messagetemp + "@";
						// 解析消息
						operationMessage(checkMessage(messagetemp));
						// 清空消息片段
						messagetemp = "";
					}
				}
			}
		}
	}

	// add by huzedong
	private String getMsgContent(String msg) {
		String temp = msg.replace("##", "");
		temp = temp.replace("@@", "");
		int ln = temp.length();
		temp = temp.substring(0, ln - 2);
		return temp.trim();
	}

	private String getCheckCode(String msg) {
		int end = msg.indexOf("@@");
		int start = end - 2;
		return msg.substring(start, end);
	}

	/**
	 * 对消息进行检测，如果消息中包含多个##，则截取最后的##到@@
	 * 
	 * @param message
	 * @author zhangsc
	 */
	private String checkMessage(String message) {
		// 如果message非空，message中包含多个##
		if (S.isNotEmpty(message) && message.split("##").length > 2) {
			StringBuffer sb = new StringBuffer(message);
			sb.reverse();
			int messageIndex = message.length() - sb.indexOf("##") - 2;
			message = message.substring(messageIndex, message.length());
		}
		return message;
	}

	/**
	 * 接收服务器字符串后的处理
	 * 
	 * @param message
	 *            服务器信息
	 */
	private void operationMessage(final String message) {

		// final String check = S.getCheckCode(getMsgContent(message));
		// final String code = getCheckCode(message);
		if (message != null) {
			// if(check.equals(code)){
			String receiveMT = S.mySubString(message, 10, 14);

			Log.i("C_MT", receiveMT + "->" + message);

			String receiveRMT = S.valueOf(MyMessage.getValue(message, MessageModel.RMT, 3));
			String receiveREN = S.valueOf(MyMessage.getValue(message, MessageModel.REN, 3));
			String receiveRSN = S.valueOf(MyMessage.getValue(message, MessageModel.RSN, 3));
			String receiveENB = S.valueOf(MyMessage.getValue(message, MessageModel.ENB, 3));
			String receiveSEM = S.valueOf(MyMessage.getValue(message, MessageModel.SEM, 3)); // 发送人
			String ENB = ParameterModel.TOLOGIN_ENB;
			// SSN修改为IMEI_ID
			String SSN = ParameterModel.IMEI_ID;
			if ((receiveRSN.equals(SSN) && (S.isEmpty(ENB) || (ENB.equals(receiveREN) || ENB.equals(receiveENB))))
					|| ("SGRP".equals(receiveMT) && "SGOC".equals(receiveRMT))) {
				// 更新接收消息的时间
				ThreadManager.getInstance().updateRecMsgTime(service);
				System.out.println("接收到了可识别的" + receiveMT + "信息:" + message);
			} else {
				System.out.println("TOLOGIN_ENB=" + ENB + "，DEVICE_ID_SSN=" + SSN + "，receiveRSN=" + receiveRSN
						+ "，receiveREN=" + receiveREN + "，receiveENB=" + receiveENB);
				System.out.println("丢弃" + receiveSEM + "发送的" + receiveMT + "信息:" + message);
				// EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TEMP,
				// "丢弃"+receiveSEM+"发送的未指定接收者的"+receiveMT+"信息", false);
				return;
			}

			// 通用AK应答
			String frontTwoRMS = S.mySubString(message, 2, 4);
			if (S.isNotEmpty(frontTwoRMS)) {
				if (frontTwoRMS.equals(MessageModel.DOWN_AKANSWER)
						|| frontTwoRMS.equals(MessageModel.DOWN_AKANSWER_ANSWER)) {
					String askMessage = MessageManager.getInstance().getAKAnswer(message);

					ServiceManage.getInstance().sendMessage(askMessage);
				}
			}

			// 截获心跳与ITSD信息并处理
			if (S.isNotEmpty(receiveMT)) {
				if (receiveMT.equals(MessageModel.SGRP)) {
					if (S.isNotEmpty(receiveRMT)) {
						if (receiveRMT.equals(MessageModel.SGOC)) {
							receiveSGOCAnswer(message);
						} else if (receiveRMT.equals(MessageModel.IQRY)) {
							receiveIQRYAnswer(message);
						} else if (receiveRMT.equals(MessageModel.HBDY)) {
							receiveHBDYSGRP(message);
						} else if (receiveRMT.equals(MessageModel.TTAQ)) {
							receiveTTAQSGRP(message);
						}
					}
				} else if (ServiceManage.getInstance().getIsLogon()) {
					if (receiveMT.equals(MessageModel.ITSD)) {
						receiveITSDAnswer(message);
						return;
					} else if (receiveMT.equals(MessageModel.TTSD) || receiveMT.equals(MessageModel.TTAD)) {// 未接收的任务下发
						receiveTTSDAnswer(message);
						return;
					} else if (receiveMT.equals(MessageModel.GWSM) || receiveMT.equals(MessageModel.BDWI)) {// 工作短语信息下发
						showReceiveMessage(message);
					} else if (receiveMT.equals(MessageModel.TTUD)) {// 任务更新下发
						showReceiveTTUDMsg(message);
						return;
					} else if (receiveMT.equals(MessageModel.TRST)) {// 进程状态重置
						receiveTRSTAnswer(message);
					} else if (receiveMT.equals(MessageModel.RKOE)) {// 其它设备强行登录
						receiveRKOEAnswer(message);
					} else if (receiveMT.equals(MessageModel.TMRS)) {
						// receiveTMRSAnswer(message);
					} else if (receiveMT.equals(MessageModel.DYHB)) {
						showReceiveDYHBMessage(message);
					} else if (receiveMT.equals(MessageModel.BLRQ)) {
						receiveBLRQMessage(message);
					} else if (receiveMT.equals(MessageModel.BLDT)) {
						receiveBLDTMessage(message);
					} else if (receiveMT.equals(MessageModel.BLPT)) {
						// receiveBLPTMessage(message);
					} else if(receiveMT.equals(MessageModel.UCUB)){
						receiveUCUBMessage(message);
					} else if (receiveMT.equals(MessageModel.CDOF)) {// 班组成员被剔出
						receiveCDOFMessage(message);
					} else if (receiveMT.equals(MessageModel.TLMF)) {// 翻行李推送
						receiveTLMFMessage(message);
					}
				}
			}
		}
		// }
		service.getMyHandler().post(new Runnable() {

			@Override
			public void run() {
				// if(check.equals(code)){
				// Body.getInstance().operateServerInfo(message);
				String rms = MyMessage.getValue(message, MessageModel.RMS, 3);
				ServiceManage.getInstance().clearWaitDialog(rms);
				// }
			}
		});

		try {
			Thread.sleep(10);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private QueryParams readerTTAQObject(String msg) {
		ObjectMapper mapper = DataManager.getInstance().getMapper();
		QueryParams query = null;
		try {
			query = mapper.readValue(msg, QueryParams.class);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return query;
	}

	private MessageTemplates readerDYMBObject(String msg) {
		ObjectMapper mapper = DataManager.getInstance().getMapper();
		MessageTemplates msgtemplates = null;
		try {
			msgtemplates = mapper.readValue(msg, MessageTemplates.class);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return msgtemplates;
	}

	/**
	 * 人车绑定车号变更
	 * @param message
	 */
	private void receiveUCUBMessage(final String message) {
		String txt = S.valueOf(MyMessage.getTxtContent(message));
		UserInfoBean userInfo = JavaBeanManager.getInstance().getUserinfo();
		if(userInfo!=null){
			userInfo.setVnb(null);
			//将车号保存到接收任务中
			LinkedHashMap<String,Task> receiveList = DataManager.getInstance().getReceiveTaskList();
			if(receiveList!=null){
				Set<String> receiveSet = receiveList.keySet();
				for(String key:receiveSet){
					Task task = receiveList.get(key);
					if(task!=null&&task.getTaskInfo()!=null){
						task.getTaskInfo().setVNB(null);
					}
				}
			}
			//将车号保存到工作任务中
			LinkedHashMap<String,Task> workList = DataManager.getInstance().getWorkTaskList();
			if(workList!=null){
				Set<String> workSet = workList.keySet();
				for(String key:workSet){
					Task task = workList.get(key);
					if(task!=null&&task.getTaskInfo()!=null){
						task.getTaskInfo().setVNB(null);
					}
				}
			}
			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, txt, false);
			ActionManager.getInstance().updateUI(MessageModel.UCUB);
		}
	}

	/**
	 * 航班单据打印确认
	 * 
	 * @param message
	 */
	private void receiveBLPTMessage(final String message) {

		String fke = S.valueOf(MyMessage.getValue(message, MessageModel.FKE, 3));
		String sts = S.valueOf(MyMessage.getValue(message, MessageModel.STS, 3));

		if ("S".equals(sts)) {
			String btp = S.valueOf(MyMessage.getValue(message, MessageModel.BTP, 3));

			DocumentResult docResult = DataManager.getInstance().getDocList(fke);
			for (Document doc : docResult.getDocumentList()) {
				if (btp.equals(doc.getBTP())) {
					doc.setSTS(sts);
					EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, context.getString(R.string.printSucceed), false);
					// Body.getInstance().updateUI(fke,ParameterModel.UI_UPDATE_DOCSUCCESS);
					break;
				}
			}
		} else {
			String ems = S.valueOf(MyMessage.getValue(message, MessageModel.EMS, 3));
			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, ems, false);
		}
	}

	/**
	 * 航班单据信息摘要查询
	 * 
	 * @param message
	 */
	private void receiveBLRQMessage(final String message) {

		String fke = S.valueOf(MyMessage.getValue(message, MessageModel.FKE, 3));
		String sts = S.valueOf(MyMessage.getValue(message, MessageModel.STS, 3));

		if ("S".equals(sts)) {
			if (S.isNotEmpty(fke)) {
				String doctxt = S.valueOf(MyMessage.getTxtContent(message));

				if (S.isEmpty(doctxt)) {
					return;
				}
				try {
					ObjectMapper mapper = DataManager.getInstance().getMapper();
					DocumentResult newdocList = mapper.readValue(doctxt, DocumentResult.class);
					DocumentResult oldDocList = DataManager.getInstance().getDocList(fke);
					// 如果没有单据摘要信息，刷新摘要信息
					if (oldDocList == null || oldDocList.getDocumentList().size() == 0) {
						DataManager.getInstance().putDocList(fke, newdocList);
						// Body.getInstance().updateUI(fke,ParameterModel.UI_UPDATE_DOCREMARK);
					} else {
						// 比较获取单据的版本号
						outter: for (Document newdoc : newdocList.getDocumentList()) {
							for (Document olddoc : oldDocList.getDocumentList()) {
								if (S.isNotEmpty(newdoc.getBTP()) && olddoc.getBTP().equals(newdoc.getBTP())) {
									String newBNO = S.valueOf(newdoc.getBNO());
									String oldBNO = olddoc.getBNO();
									// 如果新版本的版本号大于旧版本的版本号刷新页面
									if (newBNO.compareTo(oldBNO) > 0) {
										DataManager.getInstance().putDocList(fke, newdocList);
										// Body.getInstance().updateUI(fke,ParameterModel.UI_UPDATE_DOCREMARK);

										// 播放提示音
										playEffect(MessageModel.BLRQ);
										EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, context.getString(R.string.updateBill), false);
										break outter;
									}
								}
							}
						}

					}
				} catch (JsonParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JsonMappingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 航班单据详细信息查询
	 * 
	 * @param message
	 */
	private void receiveBLDTMessage(final String message) {

		String fke = S.valueOf(MyMessage.getValue(message, MessageModel.FKE, 3));
		String sts = S.valueOf(MyMessage.getValue(message, MessageModel.STS, 3));

		if ("S".equals(sts)) {
			if (S.isNotEmpty(fke)) {
				String doctxt = S.valueOf(MyMessage.getTxtContent(message));
				String btp = S.valueOf(MyMessage.getValue(message, MessageModel.BTP, 3));

				DocumentResult docResult = DataManager.getInstance().getDocList(fke);
				for (Document doc : docResult.getDocumentList()) {
					if (btp.equals(doc.getBTP())) {
						doc.setTXT(doctxt);
						// Body.getInstance().updateUI(fke,ParameterModel.UI_UPDATE_DOCDETAIL);
						break;
					}
				}

			}
		} else {
			String ems = S.valueOf(MyMessage.getValue(message, MessageModel.EMS, 3));
			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, ems, false);
		}
	}

	/**
	 * 班组成员被剔除
	 * @param message
	 */
	private void receiveCDOFMessage(String message) {
		String empNo = S.valueOf(MyMessage.getValue(message, MessageModel.WORK_GROUP_EMPNO, 3));
//		String kickTime = S.valueOf(MyMessage.getValue(message, MessageModel.WORK_GROUP_KICK_TIME, 3));

		// 移除本地此班组成员
		WorkGroupLoadMembersResponseVO workGroupLoadInfo = JavaBeanManager.getInstance().getWorkGroupLoadInfo();
		if (workGroupLoadInfo != null) {
			List<Member> members = workGroupLoadInfo.getMembers();
			if (members != null && !members.isEmpty()) {
				Iterator<Member> iterator = members.iterator();
				while (iterator.hasNext()) {
					Member next = iterator.next();
					if (empNo.equals(next.getMember_usno())) {
						iterator.remove();
						break;
					}
				}
			}
		}

		// 消息发送到页面
		String ttsMsg = context.getString(R.string.work_group_member_removed, empNo);
		EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_UPTO, ttsMsg, false);
		ActionManager.getInstance().updateUI(MessageModel.CDOF);
	}

	/**
	 * 翻行李信息推送
	 * @param message
	 */
	private void receiveTLMFMessage(String message) {
		String luggageInfo = MyMessage.getTxtContent(message);
		if (TextUtils.isEmpty(luggageInfo)) {
			return;
		}
		try {
			FindLuggageInfoResponseVO findLuggageResponseInfo = DataManager.getInstance().getMapper().readValue(luggageInfo, FindLuggageInfoResponseVO.class);
			if (findLuggageResponseInfo == null
					|| findLuggageResponseInfo.getLuggageMessageVoList() == null
					|| findLuggageResponseInfo.getLuggageMessageVoList().isEmpty()) {
				return;
			}

			// 加入本地翻行李信息
			FindLuggageDataManager.getInstance().addListFindLuggageInfo(findLuggageResponseInfo);

			// 接收到翻行李消息播报
			String fln = findLuggageResponseInfo.getFlno();
			if (TextUtils.isEmpty(fln)) return;

			String msg = DataBaseManager.getInstance().getContext().getString(R.string.find_luggage_receive_message, fln);
			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, msg, true);
			// 刷新页面
            ActionManager.getInstance().updateUI(MessageModel.TLMF);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void receiveRKOEAnswer(final String message) {
		// 判断是否为超级管理员登录
		UserInfoBean userinfo = JavaBeanManager.getInstance().getUserinfo();
		boolean userIsAdmin = false;
		if (userinfo != null) {
			userIsAdmin = userinfo.getIsadmin();// 是否为管理员
		}
		if (userIsAdmin || userinfo == null) {
			return;
		}
		// 设置发送消息不可用
		ServiceManage.getInstance().setSendMsgFlag(false);
		service.getMyHandler().post(new Runnable() {

			@Override
			public void run() {
				ShowToast.get().show(MyMessage.getValue(message, MessageModel.TXT, 3));
					WriteLog.getInstance().writeLog(context.getString(R.string.rkoe));
				ServiceManage.getInstance().onLogonOut();

				EffectManager.getInstance().vibrate();
				EffectManager.getInstance().playSound(ParameterModel.MUSIC_EFFECT_USER_OFFLINE);
				S.startActivity(MainActivity.class);

				DataBaseManager.getInstance().getContext()
						.sendBroadcast(new Intent(SecurityResponseImpl.ACTION_LOGOUT));
			}
		});
	}

	// 接收TTAQ的SGRP消息
	private void receiveTTAQSGRP(final String message) {
		service.getMyHandler().post(new Runnable() {
			@Override
			public void run() {

				String lastLockMsg = MessageManager.getInstance().getLastLockMessage();
				if (S.isEmpty(lastLockMsg)) {
					return;
				}
				String sendMS = S.mySubString(lastLockMsg, 2, 9);
				String receiveRMS = S.valueOf(MyMessage.getValue(message, MessageModel.RMS, 3));
				if (!sendMS.equals(receiveRMS)) {
					return;
				}

				String sts = S.valueOf(MyMessage.getValue(message, MessageModel.STS, 3));
				String ope = S.valueOf(MyMessage.getValue(message, MessageModel.SUB_FLIGHT_OPE, 3));
				String ems = S.valueOf(MyMessage.getValue(message, MessageModel.EMS, 3));
				if (sts.equals("S")) {
					// TTAQ初始化未成功时，queryList的内容为空
					if (JavaBeanManager.getInstance().getQueryList() == null) {
						return;
					}
					QueryParams queryParams = null;
					try {
						String content = S.getCDATAInfo(lastLockMsg);
						ObjectMapper mapper = DataManager.getInstance().getMapper();
						queryParams = mapper.readValue(content, QueryParams.class);
					} catch (JsonParseException e) {
						e.printStackTrace();
					} catch (JsonMappingException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
					if (ope.equals("Y")) {

						for (Query query : queryParams.getQueryParams()) {
							JavaBeanManager.getInstance().getQueryList().add(query);
							String sammaryName = TaskUtil.getSumProjectName(query.getTYPE());
							EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK,
									context.getString(R.string.add) + sammaryName + ":" + query.getVALUE() + context.getString(R.string.lockSucceed), false);
						}

					} else if (ope.equals("N")) {

						List<Query> delQueryList = new ArrayList<Query>();
						for (Query query : queryParams.getQueryParams()) {
							List<Query> oldQueryList = JavaBeanManager.getInstance().getQueryList();
							for (Query oldQuery : oldQueryList) {
								// 如果删除项内容与保存的锁定内容相同，删除对应项
								if (query.getRTP().equals(oldQuery.getRTP())
										&& query.getTYPE().equals(oldQuery.getTYPE())
										&& query.getVALUE().equals(oldQuery.getVALUE())) {
									delQueryList.add(oldQuery);
									break;
								}
							}
						}

						for (Query delQuery : delQueryList) {
							JavaBeanManager.getInstance().getQueryList().remove(delQuery);
							String sammaryName = TaskUtil.getSumProjectName(delQuery.getTYPE());
							EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK,
									context.getString(R.string.delete) + sammaryName + ":" + delQuery.getVALUE() + context.getString(R.string.lockSucceed), false);
						}

					}
					// Body.getInstance().updateUI(ope,
					// ParameterModel.UI_UPDATE_LOCK);
				} else {
					EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, context.getString(R.string.operatFailed) + ems, false);
				}
			}
		});
	}

	// add by huzedong
	private void receiveHBDYSGRP(final String message) {
		service.getMyHandler().post(new Runnable() {
			@Override
			public void run() {
				String lastSubMsg = MessageManager.getInstance().getLastSubMessage();
				if (S.isEmpty(lastSubMsg)) {
					return;
				}
				String sendMS = S.mySubString(lastSubMsg, 2, 9);
				String receiveRMS = S.valueOf(MyMessage.getValue(message, MessageModel.RMS, 3));
				if (!sendMS.equals(receiveRMS)) {
					return;
				}
				String sts = S.valueOf(MyMessage.getValue(message, MessageModel.STS, 3));
				String ope = S.valueOf(MyMessage.getValue(message, MessageModel.SUB_FLIGHT_OPE, 3));
				String ems = S.valueOf(MyMessage.getValue(message, MessageModel.EMS, 3));
				if (sts.equals("S")) {
					String fke = S.valueOf(MyMessage.getValue(lastSubMsg, MessageModel.FKE, 3));
					if (ope.equals("Y")) {
						if (JavaBeanManager.getInstance().getSUBFlightList() != null) {
							String fln = S.valueOf(
									MyMessage.getValue(lastSubMsg, MessageModel.strTxtValue[MessageModel.nFLN], 3));
							SubFlightInfo info = new SubFlightInfo();
							info.setFlno(fln);
							info.setFlseq(fke);
							JavaBeanManager.getInstance().getSUBFlightList().add(info);
						}
						EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, context.getString(R.string.subSucceed), false);
					} else if (ope.equals("N")) {
						List<SubFlightInfo> subList = JavaBeanManager.getInstance().getSUBFlightList();
						if (subList == null) {
							return;
						}
						int i = -1;
						for (SubFlightInfo subInfo : subList) {
							i++;
							if (subInfo.getFlseq().equals(fke)) {
								break;
							}
						}
						if (i > -1 && subList.size() > i) {
							// 删除订阅的信息
							subList.remove(i);
						}
						// 删除航班变更消息
						JavaBeanManager.getInstance().removeFlightchange(fke);
						// Body.getInstance().updateUI("",
						// ParameterModel.UI_UPDATE_SUB);
						EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, context.getString(R.string.deleteSubSucceed), false);
					}
				} else {
					EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, context.getString(R.string.subFailed) + ems, false);
				}
			}
		});
	}

	// /**
	// * 接收绑定车号返回消息
	// *
	// * @param message
	// */
	// private void receiveTRBDAnswer(final String _msg) {
	//
	// service.getMyHandler().post(new Runnable() {
	// @Override
	// public void run() {
	// TaskReceiveAction.getInstance().receiveTRBD(_msg);
	// }
	// });
	// }
	// /**
	// * 服务标注项变更
	// *
	// * @param message
	// */
	// private void receiveTMRSAnswer(final String _msg) {
	//
	// service.getMyHandler().post(new Runnable() {
	// @Override
	// public void run() {
	//
	// TaskReceiveAction.getInstance().receiveTMRS(_msg);
	//
	// }
	// });
	// }
	//
	// /**
	// * 服务标注项上报应答
	// *
	// * @param message
	// */
	// private void receiveTMRPAnswer(final String _msg) {
	//
	// service.getMyHandler().post(new Runnable() {
	// @Override
	// public void run() {
	//
	// TaskReceiveAction.getInstance().receiveTMRP(_msg);
	//
	// }
	// });
	// }
	/**
	 * 接收心跳消息应答
	 * 
	 * @param message
	 */
	private void receiveSGOCAnswer(String message) {
		// String lastSGOCMessage = MessageManager.getInstance()
		// .getlastSGOCMessage();
		// if (S.isNotEmpty(lastSGOCMessage)) {
		// String sendMT;
		// String sendMS;
		// String receiveRMT;
		String receiveRMS;
		// sendMT = S.mySubString(lastSGOCMessage, 10, 14);
		// sendMS = S.mySubString(lastSGOCMessage, 2, 9);
		// receiveRMT = MyMessage.getValue(message, MessageModel.RMT, 3);
		receiveRMS = MyMessage.getValue(message, MessageModel.RMS, 3);

		if (S.isNotEmpty(receiveRMS)) {
			// if (receiveRMT.equals(sendMT) && receiveRMS.equals(sendMS))
			// {// 心跳信息
			// // MessageManager.getInstance().clearLastSGOCMessage();
			// }
			ThreadManager.getInstance().checkMessageNumber(service, receiveRMS);
		}
		// }
	}

	/**
	 * 接收IQRY消息应答
	 * 
	 * @param message
	 */
	private void receiveIQRYAnswer(String message) {
		String lastIQRYMessage = MessageManager.getInstance().getLastIQRYMessage();
		if (S.isNotEmpty(lastIQRYMessage)) {
			String sendMT;
			String sendMS;
			String receiveRMT;
			String receiveRMS;
			sendMT = S.mySubString(lastIQRYMessage, 10, 14);
			sendMS = S.mySubString(lastIQRYMessage, 2, 9);
			receiveRMT = MyMessage.getValue(message, MessageModel.RMT, 3);
			receiveRMS = MyMessage.getValue(message, MessageModel.RMS, 3);

			if (S.isNotEmpty(sendMS) && S.isNotEmpty(receiveRMS)) {
				if (receiveRMT.equals(sendMT) && receiveRMS.equals(sendMS)) {
					// 接收成功 不知做何处理
				}
			}
		}
	}

	/**
	 * 接收ITSD消息应答
	 *
	 * @param message
	 */
	private void receiveITSDAnswer(final String message) {

		// TaskReceiveAction.getInstance().receiveITSD(message);
	}

	/**
	 * 接收TTSD消息应答
	 *
	 * @param message
	 */
	private void receiveTTSDAnswer(final String message) {
		 service.getMyHandler().post(new Runnable() {
			 @Override
			 public void run() {
				 TaskReceiveAction.getInstance().receiveTTSD(message);
			 }
		 });
	}

	private void playEffect(String type) {
		if (type.equals(MessageModel.BDWI)) {
//			int product = EffectManager.RECEIVE_PRODUCT_TYPE;// 收到生产通告时(0：震动
//			// 1：声音,2：震动+声音)
//			if (product == 0) {
//				EffectManager.getInstance().vibrate();
//			} else if (product == 1) {
//				EffectManager.getInstance().playSound(ParameterModel.MUSIC_EFFECT_RECEIVE_INFO);
//			} else {
//				EffectManager.getInstance().vibrate();
//				EffectManager.getInstance().playSound(ParameterModel.MUSIC_EFFECT_RECEIVE_INFO);
//			}
			EffectManager.getInstance().playSound(ParameterModel.MUSIC_EFFECT_RECEIVE_TASK);

		} else if (type.equals(MessageModel.GWSM)) {
//			int info = EffectManager.RECEIVE_INFO_TYPE;// 收到消息时(0：震动
//			// 1：声音,2：震动+声音)
//
//			if (info == 0) {
//				EffectManager.getInstance().vibrate();
//			} else if (info == 1) {
//				EffectManager.getInstance().playSound(ParameterModel.MUSIC_EFFECT_RECEIVE_INFO);
//			} else {
//				EffectManager.getInstance().vibrate();
//				EffectManager.getInstance().playSound(ParameterModel.MUSIC_EFFECT_RECEIVE_INFO);
//			}

			EffectManager.getInstance().playSound(ParameterModel.MUSIC_EFFECT_RECEIVE_INFO);
		} else if (type.equals(MessageModel.BLRQ)) // 单据更新提示音
		{
			int info = EffectManager.DOC_UPDATE_TYPE;// 收到消息时(0：震动
			// 1：声音,2：震动+声音)

			if (info == 0) {
				EffectManager.getInstance().vibrate();
			} else if (info == 1) {
				EffectManager.getInstance().playSound(ParameterModel.MUSIC_EFFECT_DOC_UPDATE);
			} else {
				EffectManager.getInstance().vibrate();
				EffectManager.getInstance().playSound(ParameterModel.MUSIC_EFFECT_DOC_UPDATE);
			}

		} else {// 处理收到任务
			//EffectManager.getInstance().vibrate();
			EffectManager.getInstance().playSound(ParameterModel.MUSIC_EFFECT_RECEIVE_TASK);
		}
	}

	/**
	 * 处理TRST信息
	 *
	 */
	private void receiveTRSTAnswer(final String _msg) {
		service.getMyHandler().post(new Runnable() {
			@Override
			public void run() {
				TaskReceiveAction.getInstance().receiveTRST(_msg);
			}
		});
	}

	private void showReceiveDYHBMessage(final String message) {
		service.getMyHandler().post(new Runnable() {
			@Override
			public void run() {

				FlightQueryValueChanged flightChange = readerFlightInfo(message);
				if (flightChange == null) {
					return;
				}
				DataManager.getInstance().getFlightChangeMsgList().add(flightChange);
				JavaBeanManager.getInstance().addFlightchange(flightChange);
				playEffect(MessageModel.BDWI);
				// 播放提示音
				EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, context.getString(R.string.flightChange) + FlnChangeUtils.flnChangeUtils(flightChange.getFlightQueryValue().getFLN(), context), true);
				saveData(flightChange.getFlightQueryValue().getFKE(), flightChange.getMsg(), MessageModel.DYHB);
			}
		});
	}

	private void saveData(String fke, String msg, String serviceId) {
		BoxDBHelper dbm = new BoxDBHelper(DataBaseManager.getInstance().getContext());
		dbm.setFlightData(fke, msg, serviceId, null);
		dbm.closeDB();
		DataManager.getInstance().addUnCheckNumber();
		// 刷新任务列表UI或者刷新任务详情UI
		ActionManager.getInstance().refreshBox(MessageModel.REFRESH_BOXFLIGHT);
		ActionManager.getInstance().updateUI(MessageModel.REFRESH_BOXFLIGHT);
	}

	private FlightQueryValueChanged readerFlightInfo(String msg) {
		ObjectMapper mapper = DataManager.getInstance().getMapper();
		FlightQueryValueChanged info = null;
		String txt = MyMessage.getTxtContent(msg);
		if (S.isNotEmpty(txt)) {
			try {
				info = mapper.readValue(txt, FlightQueryValueChanged.class);
			} catch (JsonParseException e) {
				e.printStackTrace();
			} catch (JsonMappingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return info;
	}

	// 跳转到任务更新页
	private void showReceiveTTUDMsg(final String _sMsg) {

		service.getMyHandler().post(new Runnable() {
			@Override
			public void run() {
				TaskReceiveAction.getInstance().receiveTTUD(_sMsg);
			}
		});
	}

	private void showReceiveMessage(final String message) {

		Log.i("C_msg", "" + message);
		String sTgn = MyMessage.getValue(message, MessageModel.TGN, 3);
		if (DataManager.getInstance().hasMsg(sTgn)) {
			WriteLog.getInstance().writeLog(context.getString(R.string.errorMessage2) + message);
			return;
		}
		MyMessageBean msg = MessageUtil.analysesMessage(message);
		Log.d("C_msg", "begin check msg");
		//重复消息不处理
		MyBeanTempDBHelper<MyMessageBean> messageDBHelper = new MyBeanTempDBHelper<MyMessageBean>(
				DataBaseManager.getInstance().getContext(), MyMessageBean.class);
		String sql = "select count(*) from " + messageDBHelper.getTableName() + " where tgn = '" + msg.getTGN() + "' and sem is not null and sem !=''";
		SQLiteDatabase db = messageDBHelper.getReadableDatabase();
		Cursor cursor = db.rawQuery(sql, null);
		cursor.moveToFirst();
		if (cursor.getInt(0) != 0) {
			return;
		}
		cursor.close();
		db.close();
		Log.d("C_msg", "sql:" + sql);
		saveToSqlite(msg);
		// 发送有新短语到达通知
		Context context = DataBaseManager.getInstance().getContext();
		if (null != context) {
			context.sendBroadcast(new Intent(ACTION_MESSAGE_ARRIVED));
		}
		playEffect(MessageModel.GWSM);
	}

	private void saveToSqlite(MyMessageBean message) {
		MyBeanTempDBHelper<MyMessageBean> messageDBHelper = new MyBeanTempDBHelper<MyMessageBean>(
				DataBaseManager.getInstance().getContext(), MyMessageBean.class);
		messageDBHelper.insert(message);
		DataManager.getInstance().addUnCheckNumber();
		// 刷新任务列表UI或者刷新任务详情UI
		ActionManager.getInstance().refreshBox(MessageModel.REFRESH_BOXMESSAGE);
		ActionManager.getInstance().updateUI(MessageModel.REFRESH_BOXMESSAGE);
		Log.d("C_db", "save message ok");
	}
}
